package com.macro.mall.portal.config;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class LocalCache<T> {
    private Cache<String,T> localCache = null;
    @PostConstruct
    public void initLocalCache(){
        localCache = CacheBuilder.newBuilder()
                //设置本地缓存容器的初始容量
                .initialCapacity(10)
                //设置写缓存后多少秒过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 设置本地缓存
     * @author tan
     * @date 2024/4/24 15:16
     * @param key
     * @param value
     */
    public void setLocalCache(String key,T value){
        localCache.put(key,value);
    }
    /**
     * 获取本地缓存
     * @author tan
     * @date 2024/4/24 15:17
     * @param key
     * @return T
     */
    public <T>T getLocalCache(String key){
        return (T)localCache.getIfPresent(key);
    }
    /**
     * 使某个key失效
     * @author tan
     * @date 2024/4/24 15:18
     * @param key
     */
    public void removeLocalCache(String key){
        localCache.invalidate(key);
    }
}
